<template>
	<div class="lianxian">
		<div class="question">
			<div class="title">
				<span>{{ questIndex }}.连线题</span>
			</div>
			<div class="question">
				<template v-for="(item,index) in question.quest.question[0].value" :key = "index">
					<p v-if="item !==''" dir="auto">
						{{ item }}
					</p>
				</template>
				<template v-for="(item,index) in question.quest.subQuestion[0].question" :key ="index">
					<template v-if="item.type ==='text'">
						<p v-for="(item1,index1) in item.value" :key = "index1">
							{{ item1 }}
						</p>
					</template>
					<template v-else-if="item.type==='audio'">
						<div class="iconBox">
							<img src="@/assets/audio.png" @click="handlePlay(item.value)">
						</div>
					</template>
					<template v-else-if="item.type==='picture'">
						<div class="iconBox">
							<el-image
								style="width: 150px; height: 150px"
								:src="item.value"
								:preview-src-list="[String(item.value)]"
								:initial-index="0"
								fit="contain"
							/>
						</div>
					</template>
					<template v-else-if="item.type==='video'">
						<div class="iconBox">
							<video controls width="250">
								<source :src="item.value" type="video/webm"/>
							</video>
						</div>
					</template>
				</template>

				<div class="answer" >
					<div class="rows" v-for="(item,index) in question.quest.subQuestion[0].constraint.value[0]">
						<div
							dir = "auto"
							:class="['option', isActived(Number(index), 0)]"
							@click = "highlight(Number(index),0,$event)"
						>
							{{item}}
						</div>
						<template v-if="optionType(1) === 'text'">
							<div
								dir = "auto"
								:class="['option', isActived(Number(index), 1)]"
								@click = "highlight(Number(index),1,$event)"
							>
								{{question.quest.subQuestion[0].constraint.value[1][index]}}
							</div>
						</template>
						<template v-if="optionType(1) === 'picture'">
							<div
								@click = "highlight(Number(index),1,$event)"
								class="resourceAnswer"
							>
								<div
									:class="['option', isActived(Number(index), 1)]"
								>
								</div>
								<div class="source">
									<el-image
										:src="question.quest.subQuestion[0].constraint.value[1][index]"
										fit="contain"
										:preview-src-list="[question.quest.subQuestion[0].constraint.value[1][index]]"
										:initial-index="0"
										@click.stop
									/>
								</div>
							</div>
						</template>
						<template v-if="optionType(1) === 'audio'">
							<div
								@click = "highlight(Number(index),1,$event)"
								class="resourceAnswer"
							>
								<div
									:class="['option', isActived(Number(index), 1)]"
								>
								</div>
								<div class="source" @click.stop = "handlePlay(question.quest.subQuestion[0].constraint.value[1][index])">
									<el-icon><Headset /></el-icon>
								</div>
							</div>
						</template>
					</div>

					<canvas :id="'myCanvas'+seq" class="myCanvas"></canvas>

				</div>
			</div>

		</div>

	</div>
</template>
<script setup lang="ts">

import {toRefs, defineProps, reactive, onMounted, PropType, Ref} from 'vue'
import {Headset, Service} from "eleicon";
import {useDataStore} from "@/stores/useDataStore";


const props = defineProps({
	//子组件接收父组件传递过来的值
	question: {
		type: Object as PropType<{ quest: {subQuestion: Array<any>,question: Array<any>}, seqNum: number }>,
	},
	questIndex: {
		type: Number
	},
	seq: {
		type: Number
	}
})

const { question,questIndex,seq } = toRefs(props) as { question: Ref<{ quest: { subQuestion: Array<any> ,question: Array<any>}, seqNum: number }>, questIndex: Ref<number>,seq: Ref<number>}

const userAnswerState = useDataStore();
interface Position {
	row: string | number;
	col: string | number;
	y: number;
}

type Pair = Position[];


const state = reactive<{
	marginBottom: number,
	canvasCtx: CanvasRenderingContext2D | null,
	currentPositon: Position | null,
	prePositon: Position | null ,
	pair: Position[] ,
	pairs: Pair[],
	scale: number,
	answer: {leftIndex:number,rightIndex:number}[],
}>({
	//记录每次的点击坐标
	marginBottom: 20,
	canvasCtx: null,
	currentPositon:  null ,
	prePositon:  null,
	pair:  [],
	pairs:  [],
	scale: 1,
	answer: []
})



onMounted(() => {
	// 初始化canvas
	const canvas = document.getElementById('myCanvas'+seq.value) as HTMLCanvasElement;
	if (canvas) {
		state.canvasCtx = canvas.getContext("2d");
	}
})



const handlePlay = (source: string) => {
	setUserAnswer();
	if (userAnswerState.currentAudio) {
		userAnswerState.currentAudio.pause(); // 暂停当前音频
		userAnswerState.currentAudio = null; // 释放当前音频
	}

	userAnswerState.currentAudio = new Audio(source) as any; // 创建新的 Audio 对象
	userAnswerState.currentAudio?.play(); // 播放音频
}


const setUserAnswer = () => {
	let answer:string[] = [];
	state.answer.forEach((item) => {
		answer.push(item.leftIndex + '|' + item.rightIndex);
	})
	const payload = {
		template: question?.value?.quest.subQuestion[0].template,
		userAnswer: answer
	};
	userAnswerState.setUserAnswer(payload, seq.value-1);
	console.log(userAnswerState.userAnswer)
}

const isInPairs = (row: number | string, col: number | string): number  => {
	let returnIdx = -1;
	state.pairs.forEach((pair: Pair, idx: number) => {
		pair.forEach((position: Position) => {
			if (position.row == row && position.col == col) {
				returnIdx = idx;
				return;
			}
		});
		if (returnIdx > -1) {
			return returnIdx;
		}
	});
	return returnIdx;
}

const highlight = (i: number, j: number, event: PointerEvent) => {
	const target: HTMLElement = event.currentTarget as HTMLElement;
	const rect = target.getBoundingClientRect();

	state.currentPositon = {
		row: i,
		col: j,
		y: rect.height / 2 + (state.marginBottom * state.scale + rect.height) * i || 0,
	};

	if (state.prePositon) {
		if (state.currentPositon.col == state.prePositon.col) {
			state.prePositon = state.currentPositon;
		} else {
			// 已经连线过
			const pairIdx = isInPairs(i, j);
			// 删除重新连线的内容
			if (pairIdx > -1) {
				state.pairs.splice(pairIdx, 1);
				state.answer.splice(pairIdx,1);
			}

			const prePairIdx = isInPairs(state.prePositon.row, state.prePositon.col);
			if (prePairIdx > -1) {
				state.pairs.splice(prePairIdx, 1);
				state.answer.splice(prePairIdx,1);
			}

			// 按照列大小进行排序顺序
			if (state.prePositon.col < state.currentPositon.col) {
				state.pair.push(state.prePositon);
				state.pair.push(state.currentPositon);
			} else {
				state.pair.push(state.currentPositon);
				state.pair.push(state.prePositon);
			}

			state.pairs.push(state.pair);
			// 记录答案
			state.answer.push({leftIndex: Number(state.pair[0].row), rightIndex: Number(state.pair[1].row)});
			// console.log(state.answer)
			setUserAnswer();
			// 画线
			drawLines();

			state.pair = [];
			state.currentPositon = null;
			state.prePositon = null;
		}
	} else {
		state.prePositon = state.currentPositon;
	}
}


const drawLines = () =>{
	if (!state.canvasCtx) {
		return;
	}
	const {width, height} = state.canvasCtx.canvas.getBoundingClientRect();
	state.canvasCtx.canvas.height = height;
	state.canvasCtx.canvas.width = width;
	state.canvasCtx.clearRect(0, 0, width, height);
	state.canvasCtx.lineWidth = 1;
	state.canvasCtx.strokeStyle = "#ddd";
	state.canvasCtx.strokeStyle = "black";
	state.canvasCtx.beginPath();
	for (let i = 0; i < state.pairs.length; i++) {
		const pairs = state.pairs[i];
		const firstColumn = pairs[0];
		state.canvasCtx.moveTo(0, firstColumn.y);
		for (let j = 1; j < pairs.length; j++) {
			const iterColumn = pairs[j];
			state.canvasCtx.lineTo(width, iterColumn.y);
		}
	}
	state.canvasCtx.closePath();
	state.canvasCtx.stroke();
}

const isActived = (i: number, j: number) => {
	if (state.currentPositon) {
		if (state.currentPositon.row == i && state.currentPositon.col == j) {
			return "actived";
		}
	}
	return "";
}

const optionType = (index:number) => {
	return question?.value?.quest.subQuestion[0].constraint.info.opType[1];
}


</script>
<style scoped lang="scss" >
.lianxian {
	box-sizing: border-box;
	:deep(.el-image) {
		text-indent: 0;
		height: 60px;
	}
	img {
		width: 30px;
		height: 30px;
		object-fit: contain;
	}

	.question {
		margin-bottom: 20px;

		.title {
			font-size: 20px;
			font-weight: 500;
			margin-bottom: 10px;
			color: #6a727f;
		}
		.dot {
			font-weight: 700;
			color: #5189dd;
			margin-right: 5px;
		}

		.question {
			font-size: 18px;
			color: #7c7787;
			text-indent: 2em;
			.iconBox {
				display: flex;
				justify-content: center;
				margin-top: 20px;
				.icon {
					font-size: 30px;
				}
			}
			.answer {
				position: relative;
				display: flex;
				flex-direction: column;
				margin-left: 100px;
				margin-top: 20px;
				.myCanvas {
					position: absolute;
					left: 140px;
					top: 20px;
					width: 100px;
					height: 100%;
				}
				.rows {
					width: 380px;
					text-indent: 0;
					display: flex;
					justify-content: space-between;

					.resourceAnswer {
						width: 120px;
						display: flex;
						padding: 10px;
						justify-content: center;
						align-items: center;
						margin-top: 20px;
						//background-color: pink;
						.option {
							width: 15px;
							height: 15px;
							display: flex;
							margin-top: 0;
							justify-content: center;
							align-items: center;
							padding: 0;
							background-color: grey;
							margin-right: 5px;
						}
						.source {
							width: 120px;

							display: flex;
							justify-content: center;
							align-items: center;
							font-size: 30px;

						}
						.actived {
							background-color: #2260fc;
							color: #F2F3F5;
						}
					}
					.option {
						width: 120px;
						display: flex;
						justify-content: center;
						align-items: center;
						margin-top: 20px;
						padding: 10px;
						background-color: #f2f3f5;
					}
					.actived {
						background-color: #2260fc;
						color: #F2F3F5;
					}

				}

			}
		}

	}
}

</style>